package com.carlinfo.users.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.carlinfo.common.util.PageInfoUtil;
import com.carlinfo.users.dao.IAUsersDao;
import com.carlinfo.users.pojo.AUsers;
import com.carlinfo.users.service.IUsersService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 用户service的实现类
 */
@Service("usersService")
public class UsersServiceImpl implements IUsersService {
    /**
     * dao如何赋值
     *      ~没有写Dao的实现类
     *      ~session.getMapper();
     */
    @Resource
    private IAUsersDao usersDao;

    @Override
    public JSONObject saveOneUsersService(AUsers users) throws Exception {
        JSONObject resultJSON = new JSONObject();
        // 返回值就是此sql语句影响的条数
        int res = this.usersDao.saveOne(users);

        /*String str = null;
        str.toString();*/

        if(res > 0) {
            JSONObject dataJSON = new JSONObject();
            dataJSON.put("effect",res + "");
            dataJSON.put("id",users.getId() + "");
            // 把数据放到resultJSON中
            resultJSON.put("data",dataJSON);

            resultJSON.put("code","0");
            resultJSON.put("info","成功");

            throw new Exception();
        } else {
            resultJSON.put("code","-1");
            resultJSON.put("info","失败");
        }
        return resultJSON;
    }

    @Override
    public AUsers findOneUsersService(Map<String, Object> condMap) {
        return this.usersDao.findOne(condMap);
    }

    /**
     * 不分页
     * 分页
     * 搜索
     */
    @Override
    public List<AUsers> findCondListUsersService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
    {
        /* 专门为关键字增加模糊匹配 */
        if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
        {
            condMap.put("keyword", "%" + condMap.get("keyword") +  "%");
        }

        if(pageInfoUtil != null)
        {
            /* 得加一个分页的标准 */
            Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
            List<AUsers> usersList = this.usersDao.findCondList(condMap);
            /* 设置一下总记录数 */
            pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
            return usersList ;
        }
        return this.usersDao.findCondList(condMap);
    }

}
